<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>分类参数</el-breadcrumb-item>
      <el-breadcrumb-item>添加商品</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片专区 -->
    <el-card class="box-card">
      <!-- 提示区域 -->
      <el-alert title="添加商品信息" type="info" :closable="false" center show-icon> </el-alert>
      <!-- 步骤条区域 -->
      <el-steps :active="activeIndex - 0" space="200px" align-center>
        <el-step title="基本信息" icon="el-icon-s-order"></el-step>
        <el-step title="商品参数" icon="el-icon-collection"></el-step>
        <el-step title="商品属性" icon="el-icon-document"></el-step>
        <el-step title="商品图片" icon="el-icon-picture"></el-step>
        <el-step title="商品内容" icon="el-icon-s-grid"></el-step>
        <el-step title="完成" icon="el-icon-circle-check"></el-step>
      </el-steps>
      <!-- 第一页的表单区域 -->

      <el-form :rules="addFromrules" label-position="top" ref="addFormRef" label-width="80px" :model="addForm">
        <el-tabs tab-position="left" v-model="activeIndex" @tab-click="tabClick" :before-leave="beforeTabLeave">
          <el-tab-pane name="0" label="基本信息">
            <el-form-item label="商品名称" prop="goods_name">
              <el-input v-model="addForm.goods_name"></el-input>
            </el-form-item>
            <el-form-item label="商品价格" prop="goods_price">
              <el-input v-model="addForm.goods_price"></el-input>
            </el-form-item>
            <el-form-item label="商品重量" prop="goods_weight">
              <el-input v-model="addForm.goods_weight"></el-input>
            </el-form-item>
            <el-form-item label="商品数量" prop="goods_number">
              <el-input v-model="addForm.goods_number"></el-input>
            </el-form-item>
            <el-form-item label="商品分类" prop="goods_cat">
              <!-- 级联选择器 -->
              <el-cascader
                v-model="addForm.goods_cat"
                :options="catelist"
                :props="cateprops"
                @change="handleChange"
              ></el-cascader>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane name="1" label="商品参数">
            <el-form-item :label="item.attr_name" v-for="item in manyTableData" :key="item.attr_id">
              <!-- 复选框组 -->
              <el-checkbox-group v-model="item.attr_vals">
                <el-checkbox :label="cb" v-for="(cb, i) in item.attr_vals" :key="i" border></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane name="2" label="商品属性">
            <el-form-item :label="item.attr_name" v-for="item in onlyTableData" :key="item.attr_id">
              <el-input v-model="item.attr_vals"></el-input>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane name="3" label="商品图片">
            <el-upload
              :action="uploadURL"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              list-type="picture"
              :headers="headerObj"
              :on-success="handleSuccess"
            >
              <el-button size="small" type="primary">点击上传</el-button>
            </el-upload>
          </el-tab-pane>
          <el-tab-pane name="4" label="商品内容">
            <!-- 富文本编辑器组件 -->
            <quill-editor v-model="addForm.goods_introduce"></quill-editor>
            <!-- 添加商品按钮 -->
            <el-button type="primary" class="btnAdd" @click="Add">添加商品</el-button></el-tab-pane
          >
        </el-tabs>
      </el-form>
    </el-card>
    <!-- 图片预览 -->
    <el-dialog title="图片预览" :visible.sync="previewVisible" width="50%">
      <img :src="previewPath" alt class="previewImg" />
    </el-dialog>
  </div>
</template>
<script>
// 导入深拷贝
import _ from 'lodash'
export default {
  data() {
    return {
      previewPath: '',
      previewVisible: false,
      // 由于用的element组件要单独写请求头
      headerObj: {
        Authorization: window.sessionStorage.getItem('token')
      },
      // 上传的地址接口文档里面
      uploadURL: 'http://127.0.0.1:8888/api/private/v1/upload',
      // 属性的数据
      onlyTableData: [],
      // 参数的数据
      manyTableData: [],
      // 配置级联选择器
      cateprops: {
        expandTrigger: 'hover',
        value: 'cat_id',
        label: 'cat_name',
        children: 'children'
      },
      // 级联选择器切换时的ID 和步骤条里的ID是一样的只不过步骤条里的ID是数字注意转换 -0  可以隐式转换
      activeIndex: '0',
      addForm: {
        goods_name: '',
        goods_price: 0,
        goods_weight: 0,
        goods_number: 0,
        // 商品所属的分类数组
        goods_cat: [],
        pics: [],
        goods_introduce: '',
        attrs: []
      },
      // 联级表单的数据
      catelist: [],
      // 表单验证规则
      addFromrules: {
        goods_name: [{ required: true, message: '请输入商品名称', trigger: 'blur' }],
        goods_price: [{ required: true, message: '请输入商品价格', trigger: 'blur' }],
        goods_weight: [{ required: true, message: '请输入商品重量', trigger: 'blur' }],
        goods_number: [{ required: true, message: '请输入商品数量', trigger: 'blur' }],
        goods_cat: [{ required: true, message: '请选择商品分类', trigger: 'blur' }]
      }
    }
  },
  created() {
    this.getcatelist()
  },
  computed: {
    cateId() {
      if (this.addForm.goods_cat.length === 3) {
        return this.addForm.goods_cat[2]
      }
      return null
    }
  },
  methods: {
    // 点击添加商品
    async Add() {
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) {
          return this.$Message.error('请填写必要的表单项！')
        }
        const form = _.cloneDeep(this.addForm)
        form.attrs = []
        form.goods_cat = form.goods_cat.join(',')

        this.manyTableData.forEach(item => {
          const newInfo = {
            attr_id: item.attr_id,
            attr_value: item.attr_vals.join(' ')
          }
          form.attrs.push(newInfo)
        })

        this.onlyTableData.forEach(item => {
          const newInfo = { attr_id: item.attr_id, attr_value: item.attr_vals }
          form.attrs.push(newInfo)
        })
        console.log(form)
        let { data: res } = await this.$axios.post('goods', form)
        if (res.meta.status !== 201) {
          return this.$Message.error('添加商品失败！' + res.meta.msg)
        }

        this.$Message.success('添加商品成功！')
        this.$router.push('/goods')
      })
    },
    // 文件上传成功时
    handleSuccess(response, file, fileList) {
      // console.log(response)
      const picInfo = { pic: response.data.tmp_path }
      this.addForm.pics.push(picInfo)
    },
    // 点击文件列表中已上传的文件时的钩子
    handlePreview(file) {
      console.log(file)
      this.previewPath = file.response.data.url
      this.previewVisible = true
    },
    // 删除时
    handleRemove(file) {
      // console.log(file)
      // const filePath = file.response.data.tmp_path
      // 1. 获取将要删除的图片的临时路径
      const filePath = file.response.data.tmp_path
      // 2. 从 pics 数组中，找到这个图片对应的索引值
      const i = this.addForm.pics.findIndex(x => x.pic === filePath)
      // 3. 调用数组的 splice 方法，把图片信息对象，从 pics 数组中移除
      this.addForm.pics.splice(i, 1)
      // console.log(this.addForm)
    },

    // 获取级联选择器的数据
    async getcatelist() {
      let { data: res } = await this.$axios.get('categories')
      console.log(res)
      if (res.meta.status !== 200) {
        return this.$Message.error('获取数据失败')
      }
      this.catelist = res.data
    },
    // 切换tab栏之前的函数 如果返回false 则会阻止跳转 activeName, oldActiveName
    beforeTabLeave(one, two) {
      // console.log('即将进入的标签页名字是：' + one)
      // console.log('即将离开的标签页名字是：' + two)
      if (two === '0' && this.addForm.goods_name === '') {
        this.$Message.error('请先输入商品名称！')
        return false
      } else if (two === '0' && this.addForm.goods_price === '') {
        this.$Message.error('请先选择商品价格！')
        return false
      } else if (two === '0' && this.addForm.goods_weight === '') {
        this.$Message.error('请先输入商品重量！')
        return false
      } else if (two === '0' && this.addForm.goods_number === '') {
        this.$Message.error('请先输入商品数量！')
        return false
      } else if (two === '0' && this.addForm.goods_cat.length !== 3) {
        this.$Message.error('请先选择商品分类！')
        return false
      }
    },
    // 级联选择器状态改变时的触发的事件
    handleChange() {
      if (this.addForm.goods_cat.length !== 3) {
        this.addForm.goods_cat = []
      }
      console.log(this.addForm.goods_cat)
    },

    // tab栏切换时的事件
    async tabClick() {
      console.log(this.activeIndex)
      if (this.activeIndex === '1') {
        let { data: res } = await this.$axios.get(`categories/${this.cateId}/attributes`, {
          params: { sel: 'many' }
        })

        if (res.meta.status !== 200) {
          return this.$Message.error('获取动态参数列表失败！')
        }
        res.data.forEach(item => {
          item.attr_vals = item.attr_vals.length > 0 ? item.attr_vals.split(' ') : []
        })
        // console.log(res)
        this.manyTableData = res.data
      } else if (this.activeIndex === '2') {
        let { data: res } = await this.$axios.get(`categories/${this.cateId}/attributes`, {
          params: { sel: 'only' }
        })

        if (res.meta.status !== 200) {
          return this.$Message.error('获取动态属性列表失败！')
        }
        this.onlyTableData = res.data
        // console.log(res)
      }
    }
  }
}
</script>
<style lang="less" scoped>
.previewImg {
  width: 100%;
}
.btnAdd {
  margin-top: 15px;
}
.el-checkbox {
  margin: 0 10px 0 0 !important;
}
</style>
